//
//  JWBaseTableView.m
//  JW_BasePorject
//
//  Created by JW on 2018/4/12.
//  Copyright © 2018年 JW. All rights reserved.
//

#import "JWBaseTableView.h"
#import "MJRefresh.h"
#import "UIScrollView+EmptyDataSet.h"


#import "UIColor+Hexadecimal.h"
static const CGFloat MJDuration = 2.0;

/**
 * 随机数据
 */
#define MJRandomData [NSString stringWithFormat:@"随机数据---%d", arc4random_uniform(1000000)]


@interface JWBaseTableView () <UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, assign) NSUInteger pageNumber;//分页标识


//@property (nonatomic, assign) BOOL notReusable;
//@property (nonatomic, getter=isLoading) BOOL loading;//是否是加载数据状态

@property (nonatomic, assign) DZNState emptyState;


@end

@implementation JWBaseTableView
//@synthesize sourceData =_sourceData;



- (void)initstance {
    self.delegate = self;
    self.dataSource = self;
    self.emptyDataSetSource = self;
    self.emptyDataSetDelegate = self;
    
    self.pageNumber = 1;
    self.emptyState = DZNDataEmpty;
    self.backgroundColor = [UIColor whiteColor];
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
}



//- (void)setLoading:(BOOL)loading
//{
//    if (self.isLoading == loading) {
//        return;
//    }
//
//    _loading = loading;
//
//    [self reloadEmptyDataSet];
//}


- (NSMutableArray *)sourceData{
    if(_sourceData == nil){
        _sourceData = [NSMutableArray array];
    }
    return _sourceData;
}

//- (void)setSourceData:(NSMutableArray *)sourceData {
//    _sourceData = sourceData;
//
//    [self reloadData];
//    if (sourceData.count == 0) {
//        if (self.emptyTitle.length == 0) {
//            self.emptyTitle = @"暂无数据";
//        }
//        [self reloadEmptyDataSet];
//    }
//}





// 注册cell

- (void)registerCellClass:(NSString *)cellClassName cellIdentifier:(NSString *)cellIdentifier modelClass:(NSString *)modelClassName{
    
    [self initstance];

    self.cellClassName = cellClassName;
    self.cellIdentifier = cellIdentifier;
    self.modelClassName = modelClassName;
    
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.sourceData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:self.cellIdentifier];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@", indexPath.row % 2?@"push":@"modal", self.sourceData[indexPath.row]];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 40;
 
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.sourceData removeAllObjects];
    [self reloadData];
    
}

#pragma mark - MJRefresh
- (void)initRefreshView{
    self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNumber = 0;
        [self loadDatas];
    }];
    self.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDatas)];
    
//    self.mj_footer.automaticallyChangeAlpha = YES;
//    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDatas)];
//    footer.automaticallyChangeAlpha = YES;
//    // 禁止自动加载
//    footer.automaticallyRefresh = NO;
//    self.mj_footer = footer;
    
}


#pragma mark - load datas

//下拉刷新 + 无数据重新加载数据
- (void)loadDatas{
    if (!self.url || !self.parameter) {
        [self.mj_header endRefreshing];
        self.emptyState = DZNDataEmpty;
        if (self.sourceData.count == 0) {
            self.emptyTitle = @"暂无数据";
            [self reloadEmptyDataSet];
        }
        return;
    }
    
    
    [self.sourceData removeAllObjects];
    // 1.添加假数据
    for (int i = 0; i<5; i++) {
        [self.sourceData insertObject:MJRandomData atIndex:0];
    }
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    __weak UITableView *tableView = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [tableView reloadData];
        // 拿到当前的下拉刷新控件，结束刷新状态
        [tableView.mj_header endRefreshing];
        if (self.emptyState == DZNDataLoading) {
            self.mj_header.hidden = NO;
            self.mj_footer.hidden = NO;
            self.emptyState = DZNDataEmpty;
        }
        

    });
    
}

//上拉加载更多数据
- (void)loadMoreDatas{
    if (!self.url || !self.parameter) {
        [self.mj_header endRefreshing];
        self.emptyState = DZNDataEmpty;
        if (self.sourceData.count == 0) {
            self.emptyTitle = @"暂无数据";
            [self reloadEmptyDataSet];
        }
        return;
    }
    
    // 1.添加假数据
    for (int i = 0; i<5; i++) {
        [self.sourceData addObject:MJRandomData];
    }
    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    __weak UITableView *tableView = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [tableView reloadData];
        
        // 拿到当前的上拉刷新控件，结束刷新状态
        [tableView.mj_footer endRefreshing];

    });
    
    
}


- (void)reloadNewData {
    [self loadDatas];
}



#pragma mark - DZNEmptyDataSetSource
//设置默认空白界面处理视图的标题Title
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = nil;
    UIFont *font = nil;
    UIColor *textColor = nil;
    
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    if (self.emptyTitle) {
        text = self.emptyTitle;
    }else{
        text = @"";
    }
    font = [UIFont systemFontOfSize:17.0];
    textColor = [UIColor grayColor];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

//设置默认空白界面处理视图的描述description文本
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = nil;
    UIFont *font = nil;
    UIColor *textColor = nil;
    
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    if (self.emptyMessage) {
        text = self.emptyMessage;
    }else{
        text = @"";
    }
    
    font = [UIFont systemFontOfSize:17.0];
    textColor = [UIColor grayColor];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
    
}

//设置空白页图片
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.emptyState == DZNDataLoading) {
        return [UIImage imageNamed:@"loading_imgBlue_78x78" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];
    }else if (self.emptyState == DZNDataEmpty) {
        return [UIImage imageNamed:@"placeholder_dropbox"];
    }else if (self.emptyState == DZNLostNetwork){
        return [UIImage imageNamed:@"placeholder_remote"];
    }else{
        return [UIImage imageNamed:@"placeholder_dropbox"];

    }
}

//设置默认空白界面图片的动画效果。
- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0) ];
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

// * 设置默认空白界面的背景颜色。默认为[UIColor clearColor]
- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor colorWithHex:@"f0f3f5"];
}
////内容视图的垂直对齐（垂直偏移量）
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return (SCREEN_HEIGHT / 2);
////    return 0;
//}
//设置界面元素的垂直间距，默认为11px。
//- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView {
//    return 0.0;
//}

#pragma mark - DZNEmptyDataSetDelegate Methods
//实现该方法告诉代理EmptyDataSetView显示时应该被渲染。默认为YES
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

//实现该方法告诉代理该视图可以响应点击事件，默认为YES。
- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return YES;
}
//实现该方法告诉代理该视图允许滚动，默认为NO。
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

// 实现该方法告诉代理该视图中的图片允许执行动画，默认为NO。 当loading时方可执行动画
- (BOOL)emptyDataSetShouldAnimateImageView:(UIScrollView *)scrollView {
    if (self.emptyState == DZNDataLoading) {
        return YES;
    }
    return NO;
}

//实现该方法告诉代理empty dataset view被点击触发
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    
    if (self.mj_header.state != MJRefreshStateIdle  || self.mj_footer.state != MJRefreshStateIdle) {
        return;
    }
    
    self.emptyState = DZNDataLoading;
    self.mj_header.hidden = YES;
    self.mj_footer.hidden = YES;
    [self reloadEmptyDataSet];
    [self reloadNewData];
    NSLog(@"点击空白视图");
}

//实现该方法告诉代理，响应按钮点击事件被触发
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {

    NSLog(@"点击按钮");

}

//emptyDataView视图即将出现
- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView{
    self.mj_footer.hidden = YES;
}

// emptyDataView视图已经消失
- (void)emptyDataSetDidDisappear:(UIScrollView *)scrollView{
    self.mj_footer.hidden = NO;
}
@end
